package com.alibaba.yygh.orders.controller;

import com.alibaba.yygh.common.exception.YyghException;
import com.alibaba.yygh.common.result.R;
import com.alibaba.yygh.enums.PaymentTypeEnum;
import com.alibaba.yygh.orders.service.PaymentInfoService;
import com.alibaba.yygh.orders.service.WeixinService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * description: WeixinController
 * @author: gql
 * @date: 2021/11
 */
@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {
    @Autowired
    private WeixinService weixinPayService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @ApiOperation("1.生成二维码")
    @GetMapping("/createNative/{orderId}")
    public R createNative(@PathVariable("orderId") Long orderId) {
        Map map = weixinPayService.createNative(orderId);
        return R.ok().data(map);
    }

    @ApiOperation(value = "2.查询支付状态")
    @GetMapping("/queryPayStatus/{orderId}")
    public R queryPayStatus(@PathVariable("orderId") Long orderId) {
        // 1.根据订单号查询微信接口,查看支付状态
        Map<String, String> resultMap = weixinPayService.queryPayStatus(orderId, PaymentTypeEnum.WEIXIN.name());
        if (resultMap == null) {
            throw new YyghException(20001,"支付失败");
        }
        if ("SUCCESS".equals(resultMap.get("trade_state"))) {
            // 更新订单状态和支付状态
            String out_trade_no = resultMap.get("out_trade_no");
            paymentInfoService.paySuccess(out_trade_no, PaymentTypeEnum.WEIXIN.getStatus(), resultMap);
            return R.ok().message("支付成功");
        }
        return R.ok().message("支付中");
    }


}
